package com.liuqi.knet.remoting.exchange.codec;

import com.liuqi.knet.remoting.Codec;
import com.liuqi.knet.remoting.exchange.support.MultiMessage;
import com.liuqi.knet.serialize.Serialization;
import io.netty.buffer.ByteBuf;
import java.io.IOException;

/**
 * 多部分解码器
 *
 * @author liuqi
 * @date 2025/3/6 13:23
 **/
public class ExchangeCountCodec implements Codec {
    ExchangeCodec codec;

    public ExchangeCountCodec(Serialization serialization) {
        this.codec = new ExchangeCodec(serialization);
    }

    @Override
    public void encode(ByteBuf buffer, Object message) throws IOException {
        codec.encode(buffer, message);
    }

    @Override
    public Object decode(ByteBuf buffer) throws IOException {
        int save = buffer.readerIndex();
        MultiMessage result = new MultiMessage();
        do {
            Object obj = codec.decode(buffer);
            if (DecodeResult.NEED_MORE_INPUT == obj) {
                buffer.readerIndex(save);
                break;
            } else {
                result.addMessage(obj);
                save = buffer.readerIndex();
            }
        } while (true);
        if (result.isEmpty()) {
            return DecodeResult.NEED_MORE_INPUT;
        }
        if (result.size() == 1) {
            return result.getFirst();
        }
        return result;
    }
}
